package com.xmtlxx.tms.service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.entity.SysUser;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.enums.UserType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.tms.domain.Carrier;
import com.xmtlxx.tms.domain.Driver;
import com.xmtlxx.tms.domain.bo.DriverBo;
import com.xmtlxx.tms.domain.vo.DriverVo;
import com.xmtlxx.tms.mapper.CarrierMapper;
import com.xmtlxx.tms.mapper.DriverMapper;
import com.xmtlxx.tms.service.IDriverService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmtlxx.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 司机Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DriverServiceImpl implements IDriverService {

    private final DriverMapper baseMapper;

    private final SysUserMapper sysUserMapper;

    private final CarrierMapper carrierMapper;

    /**
     * 查询司机
     *
     * @param id 司机主键
     * @return 司机
     */
    @Override
    public DriverVo queryById(String id){
        //return baseMapper.selectVoById(id);
        return baseMapper.selectDriverVoByID(id);
    }

    /**
     * 查询司机列表
     *
     * @param bo 司机
     * @return 司机
     */
    @Override
    public TableDataInfo<DriverVo> queryPageList(DriverBo bo, PageQuery pageQuery) {
       // LambdaQueryWrapper<Driver> lqw = buildQueryWrapper(bo);
       // Page<DriverVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<DriverVo> result = baseMapper.selectPageDriverList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询司机列表
     *
     * @param bo 司机
     * @return 司机
     */
    @Override
    public List<DriverVo> queryList(DriverBo bo) {
       // LambdaQueryWrapper<Driver> lqw = buildQueryWrapper(bo);
       // return baseMapper.selectVoList(lqw);
        return baseMapper.selectDriverList(bo);
    }

    private LambdaQueryWrapper<Driver> buildQueryWrapper(DriverBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Driver> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierId()), Driver::getCarrierId, bo.getCarrierId());
        lqw.eq(bo.getUserId() != null, Driver::getUserId, bo.getUserId());
        lqw.like(StringUtils.isNotBlank(bo.getPersonName()), Driver::getPersonName, bo.getPersonName());
        lqw.eq(StringUtils.isNotBlank(bo.getVehicleClass()), Driver::getVehicleClass, bo.getVehicleClass());
        lqw.eq(StringUtils.isNotBlank(bo.getDriverCode()), Driver::getDriverCode, bo.getDriverCode());
        lqw.eq(StringUtils.isNotBlank(bo.getFileNo()), Driver::getFileNo, bo.getFileNo());
        lqw.between(params.get("beginReceiveDateFirst") != null && params.get("endReceiveDateFirst") != null,
            Driver::getReceiveDateFirst ,params.get("beginReceiveDateFirst"), params.get("endReceiveDateFirst"));
        lqw.ge(bo.getValidPeriodFrom() != null, Driver::getValidPeriodFrom, bo.getValidPeriodFrom());
        lqw.le(bo.getValidPeriodTo() != null, Driver::getValidPeriodTo, bo.getValidPeriodTo());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Driver::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增司机
     *
     * @param bo 司机
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(DriverBo bo) {
        Driver add = BeanUtil.toBean(bo, Driver.class);
        validEntityBeforeSave(add);

        //填充UUID
        add.setId(IdUtil.simpleUUID());
        add.setDelFlag("0");
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }

        Carrier carrier = carrierMapper.selectById(bo.getCarrierId());

        SysUser user = new SysUser();
        BeanUtil.copyProperties(bo,user);
        user.setNickName(bo.getPersonName());
        user.setPassword(BCrypt.hashpw(bo.getPassword()));
        user.setUserType(UserType.APP_USER.getUserType());
        user.setDeptId(carrier.getDeptId());
        user.setPhonenumber(bo.getUserName());
        user.setTenantId(LoginHelper.getTenantId());
        flag = sysUserMapper.insert(user) > 0;

        //更新userid
        add.setUserId(user.getUserId());
        flag = baseMapper.updateById(add) > 0;

        return flag;
    }

    /**
     * 修改司机
     *
     * @param bo 司机
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(DriverBo bo) {
        Driver update = BeanUtil.toBean(bo, Driver.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Driver entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除司机
     *
     * @param ids 需要删除的司机主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
